﻿using Ay.Framework.WPF.Controls;
using MPSystem.Models;
using Base.BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;
using Ay.Framework.WPF;
using MPSystem.Views.YFQ;
using MPSystem.Util;
using System.IO;

namespace ADX.Views
{
    /// <summary>
    /// ZCYLPage.xaml 的交互逻辑
    /// </summary>
    public partial class ZCYLPage_EveryDayZLDB : Page
    {
        Common common = new Common();
        public static ZCYLPage_EveryDayZLDB Me = null;
        public static int cqbh=0,gzmbh = 0;
        private List<double> P1 = new List<double>() { 10, 34.6, 60, 80 };
        private List<double> P2 = new List<double>() { 11, 54, 70, 80 };
        private List<double> P3 = new List<double>() { 13, 45, 70, 90 };
        private List<string> test = new List<string>() { "正常", "正常1", "正常1", "正常2" };
        private List<double> P12 = new List<double>();
        private List<string> S = new List<string>() { "正常" };
        private List<double> F1 = new List<double>();
        private List<double> F2 = new List<double>();
        private List<double> F3 = new List<double>();
        private List<double> F12 = new List<double>();
        private List<double> Freq = new List<double>();
        private List<DateTime> T = new List<DateTime>();
        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set { _IsBusy = value; }
        }
        private double UpperLimit = 40;//上限值
        private double LowLimit = 20;//下限值
        private string ComanpyName = "";
        private bool FirstReflash = true;

        private string bh = "", dtStart = "", dtEnd = "", wz = "", hSpan = "", MPa = "", sfzj = "0", SYZT = "";
        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();

        public ZCYLPage_EveryDayZLDB()
        {
            InitializeComponent();
            Loaded += AyPage_Loaded;
            Me = this;
        }

        void AyPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyPage_Loaded;

            var rcq = ConfigService.GetCQ(true);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            combcq.ItemsSource = rcq;
            combcq.SelectedIndex = 0;
            //工作面
            var rgzm = ConfigService.GetGZM(rcq.ElementAt(0).CQBH);
            combgzm.ItemsSource = common.LoadCombox_IECobx(rgzm);
            if (rgzm.Count() > 0) combgzm.SelectedIndex = 1;

            ComanpyName = common.GetCompanyName();
            T_CompanyName.Text = ComanpyName + "综采每日工作阻力分布曲线图";
        }

        private void LayoutRoot_load(object sender, EventArgs e)
        {
            //SycnReflash();
        }
        


        /// <summary>
        /// 后台加载
        /// </summary>
        void SycnReflash()
        {
            var cond = DataQuery_ZCGZZL_Conditon.Me.Cond;
            if (cond.Count == 0) return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, ea) =>
            {
                //no direct interaction with the UI is allowed from this method
                AyThread.Instance.RunUI(() =>
                {
                    bh = cond["bhs"];
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    hSpan = cond["jq"];
                    MPa = cond["MPa"];
                    DataZcService dzs = new DataZcService();
                    int cq = 0, gzm = 0;//测区，工作面
                    try
                    {
                        cq = int.Parse(combcq.SelectedValue.ToString());
                        gzm = int.Parse(combgzm.SelectedValue.ToString());
                    }
                    catch
                    {
                    }

                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd)+new TimeSpan(23,59,59);
                    string[] s = bh.Split(',');
                    List<CurveZc> zcs = new List<CurveZc>();
                    int _hSpan = AyCommon.ToInt(hSpan);
                    for (int b = 0; b < s.Length; b++)
                    {
                        var zc = _hSpan==0?dzs.CurveNormal(cq, gzm,AyCommon.ToInt(s[b]), db, de):
                            dzs.CurveWeighted(cq, gzm,AyCommon.ToInt(s[b]),"",_hSpan, db, de);
                        zc.X.Add(s[b].ToString());
                        zcs.Add(zc);
                    }
                    CreateChartColumn("阻力对比分析", zcs, MPa);
                });
                //CreateChartColumn("测试", strListx, strListy);
            };
            worker.RunWorkerCompleted += (o, ea) =>
            {
                //work has completed. you can now interact with the UI
                busyin.IsBusy = false;
            };
            //set the IsBusy before you start the thread
            busyin.IsBusy = true;
            worker.RunWorkerAsync();
        }

        private bool isPick = false;
        private void Chart_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!MPSystem.SESSIONS.ShowMenu || chart.Series.Count < 2 || chart.Series[1].DataPoints.Count == 0)
            {
                return;
            }
            ContextMenu menu = new ContextMenu();
            MenuItem menuItem1 = new MenuItem();
            menuItem1.Header = isPick ? "取消标记" : "标记";
            menuItem1.Click += new RoutedEventHandler((s, ee) => {
                isPick = !isPick;
                chart.IndicatorEnabled = isPick;
                if (!isPick)
                {
                    markers.DataPoints.Clear();
                }
            });
            menu.Items.Add(menuItem1);

            MenuItem menuItem2 = new MenuItem();
            menuItem2.Header = "导出标记";
            menuItem2.IsEnabled = markers.DataPoints.Count > 0;
            menuItem2.Click += new RoutedEventHandler((s, ee) => {

                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".txt";
                dlg.Filter = "txt file|*.txt";
                dlg.CheckFileExists = false;
                if (dlg.ShowDialog() == true)
                {
                    //排序
                    List<DataPoint> sorted = markers.DataPoints.ToList();
                    sorted.Sort((x, y) =>
                    {
                        var xs = new List<string>();
                        for (int i=1;i< chart.Series.Count;i++)
                        {
                            xs.Add(chart.Series[i].LegendText);
                        }
                        int cmp = ((DateTime)x.XValue).CompareTo(y.XValue);
                        if (cmp == 0)
                        {
                            return xs.IndexOf(x.Href.ToString()).CompareTo(xs.IndexOf(y.Href.ToString()));
                        }
                        return cmp;
                    });
                    FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.NewLine = Environment.NewLine;
                    DateTime lastDate = DateTime.MinValue;
                    foreach (var dp in sorted)
                    {
                        if (lastDate != (DateTime)dp.XValue)
                        {
                            if (lastDate != DateTime.MinValue)
                            {
                                sw.WriteLine();
                            }
                            sw.WriteLine(((DateTime)dp.XValue).ToString("yyyy-MM-dd HH:mm:ss"));
                            lastDate = (DateTime)dp.XValue;
                        }
                        sw.Write(string.Format("{0}:{1:f1}{2} ", dp.Href, dp.YValue, MPa));
                    }
                    sw.Flush();
                    sw.Close();
                    AyMessageBox.Show("导出完毕！");
                }
            });
            menu.Items.Add(menuItem2);

            //MenuItem menuItem3 = new MenuItem();
            //menuItem3.Header = "导出所有";
            //menuItem3.Click += new RoutedEventHandler((s, ee) => {

            //    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            //    dlg.DefaultExt = ".txt";
            //    dlg.Filter = "txt file|*.txt";
            //    dlg.CheckFileExists = false;
            //    if (dlg.ShowDialog() == true)
            //    {
            //        FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
            //        StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            //        sw.NewLine = Environment.NewLine;
            //        for (int i = 1; i < chart.Series.Count; i++)
            //        {
            //            var series = chart.Series[i];
            //            sw.WriteLine(series.LegendText);
            //            foreach (var dp in series.DataPoints)
            //            {
            //                sw.Write(string.Format("{0}:{1:f1}{2} ", dp.XValue, dp.YValue,MPa));
            //            }
            //            sw.WriteLine();
            //        }
            //        sw.Flush();
            //        sw.Close();
            //        AyMessageBox.Show("导出完毕！");
            //    }
            //});
            //menu.Items.Add(menuItem3);
            chart.ContextMenu = menu;
        }

        private void Chart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //0：空 1：辅助标记系列 2开始：数据
            if (!isPick || chart.ToolTips.Count < 2)
            {
                return;
            }
            for (int i = 2; i < chart.ToolTips.Count; i++)
            {
                if (!chart.ToolTips[i].IsVisible || chart.ToolTips[i].Text == "")
                {
                    continue;
                }
                string[] tips = chart.ToolTips[i].Text.Split(new char[] { ',' });
                DataPoint ptClick = new DataPoint();
                ptClick.XValue = DateTime.Parse(tips[0]);
                ptClick.YValue = double.Parse(tips[1].Replace(MPa, ""));
                ptClick.Href = chart.Series[i - 1].LegendText;//保存序列日期
                //删除已选定的点
                bool isDel = false;
                for (int j = markers.DataPoints.Count - 1; j >= 0; j--)
                {
                    var pt = markers.DataPoints[j];
                    if (pt.XValue.Equals(ptClick.XValue) && pt.YValue == ptClick.YValue && pt.Href == ptClick.Href)
                    {
                        try { markers.DataPoints.Remove(pt); } catch (Exception ex) { }
                        isDel = true;
                    }
                }
                if (!isDel)
                {
                    //ptClick.MouseLeftButtonDown += new MouseButtonEventHandler((s, ee) => {
                    //    //接收到当前被点击的LengendText的值 
                    //    DataPoint dpoint = s as DataPoint;
                    //});
                    markers.DataPoints.Add(ptClick);
                }
            }
        }

        private DataSeries markers = new DataSeries();
        public void CreateChartColumn(string name, List<CurveZc> zcs, string dw)
        {
            //创建一个图标
            // Chart chart = new Chart();
            this.chart.Series.Clear();

            #region 标注功能
            if (FirstReflash)
            {
                markers.ToolTipText = "点击移除此标注";
                markers.XValueType = ChartValueTypes.DateTime;
                markers.RenderAs = RenderAs.Point;
                markers.ShowInLegend = false;
            }
            isPick = false;
            chart.IndicatorEnabled = false;
            markers.DataPoints.Clear();
            chart.Series.Add(markers);
            #endregion

            if (FirstReflash)
            {
                //设置图标的宽度和高度
                //chart.Width = 580;
                //chart.Height = 380;

                //是否启用打印和保持图片
                chart.ToolBarEnabled = false;

                //设置图标的属性
                chart.ScrollingEnabled = false;//是否启用或禁用滚动
                chart.View3D = false;//3D效果显示

                //创建一个标题的对象
                Title title = new Title();

                //设置标题的名称
                title.Text = Name;
                title.Padding = new Thickness(0, 10, 5, 0);

                //向图标添加标题
                chart.Titles.Add(title);
                //初始化一个新的Axis
                Axis xAxis = new Axis();
                AxisLabels xLabel = new AxisLabels();
                xLabel.Angle = -45;
                xAxis.AxisLabels = xLabel;
                //设置Axis的属性
                //图表的X轴坐标按什么来分类，如时分秒
                xAxis.IntervalType = IntervalTypes.Hours;
                //图表的X轴坐标间隔如2,3,20等，单位为xAxis.IntervalType设置的时分秒。
                //xAxis.Interval = 2;
                //设置X轴的时间显示格式为7-10 11：20           
                xAxis.ValueFormatString = "yyyy-MM-dd HH:mm:ss   ";
                //给图标添加Axis
                chart.AxesX.Add(xAxis);
                
                // 创建一个新的数据线。               
                //DataSeries dataSeries = new DataSeries();

                //// 设置数据线的格式
                //dataSeries.RenderAs = RenderAs.StackedColumn;//柱状Stacked
                FirstReflash = false;
            }
            chart.AxesY.Clear();
            Axis yAxis = new Axis();
            //设置图标中Y轴的最小值永远为0           
            yAxis.AxisMinimum = 0;
            yAxis.Suffix = dw;
            chart.AxesY.Add(yAxis);
            //创建第一个DataSeries
            foreach (var zc in zcs)
            {
                List<double> valuey = dw=="MPa"?zc.P12:zc.F12;
                if (valuey.Count() == 0) continue;
                DataSeries oneDataSeries = new DataSeries();
                oneDataSeries.XValueType = ChartValueTypes.DateTime;
                oneDataSeries.LabelEnabled = true;
                oneDataSeries.LabelText = "#YValue";
                oneDataSeries.LegendText = zc.X[0]+"分站";
                oneDataSeries.LineThickness = 1;
                oneDataSeries.RenderAs = RenderAs.QuickLine;

                //oneDataSeries.Color = new SolidColorBrush(DrawHelper.RandColor());
                //创建第一个DataSeries的DataPoint
                DataPoint oneDataPoint = null;
                for (int i = 0; i < valuey.Count; i++)
                {
                    oneDataPoint = new DataPoint();
                    //oneDataPoint.AxisXLabel = zc.T[i].ToString();
                    oneDataSeries.XValueFormatString = "yyyy-MM-dd HH:mm:ss";
                    oneDataSeries.YValueFormatString = "0.0'" + dw + "'";
                    oneDataPoint.XValue = zc.T[i];
                    oneDataPoint.YValue = valuey[i];
                    oneDataSeries.DataPoints.Add(oneDataPoint);
                }
                chart.Series.Add(oneDataSeries);
            }
        }

        private void btnquery_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            SycnReflash();
        }

        /// <summary>
        /// 高级查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnH_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ShowNavigationWindow("检测报表--高级查询", "/Views/YFQ/DataQuery_ZCGZZL_Conditon.xaml", 600, 500);
        }
        /// <summary>
        /// 附加信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAttac_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ShowNavigationWindow("检测报表--附加信息", "/Views/YFQ/ZCYLPage_Attac.xaml", 600, 500);
        }
        /// <summary>/// 弹出层对象/// </summary>

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing;
                // window.pas += new window.PassValuesHandler(ReceiveValues);
            }
            else
            {
                DataQuery_ZCGZZL_Conditon.Me.LoadBH();
            }
            window.ShowDialog();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            DataQuery_ZCGZZL_Conditon.Me.UpdateCond();
            window.Hide();
            Me.SycnReflash();
            e.Cancel = true;
        }


        private void combcq_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combcq.SelectedValue == null) return;
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            var gzmSource = ConfigService.GetGZM(cqbh);
            combgzm.ItemsSource = common.LoadCombox_IECobx(gzmSource);
            if (gzmSource.Count() > 0) combgzm.SelectedIndex = 1;
        }
    }
}
